﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GameFramework;
using UnityGameFramework.Runtime;

namespace MYSTARFORCE {
    public class Weapon : AccessoryObject
    {
        private const string AttachPoint = "Weapon Point";

        private WeaponData m_WeaponData = null;

        private float m_NextAttackTime = 0f;

        protected override void OnShow(object userData)
        {
            base.OnShow(userData);

            m_WeaponData = userData as WeaponData;
            if(m_WeaponData == null)
            {
                Log.Warning("Weapon Data is invalid");
                return;
            }

            GameEntry.Entity.AttachEntity(Entity, m_WeaponData.Owner, AttachPoint);
        }

        protected override void OnAttachTo(EntityLogic parentEntity, Transform parentTransform, object userData)
        {
            base.OnAttachTo(parentEntity, parentTransform, userData);
            CachedTransform.localPosition = Vector3.zero;
        }

        public void TryAttack()
        {
            // 把下一次攻击的时间设定为：当前时间+CD时间
            // 如果下一次开火的时候，发现当前时间>前一次的时间，就允许开火。
            if (Time.time < m_NextAttackTime)
            {
                return;
            }

            m_NextAttackTime = Time.time + m_WeaponData.AttackInterval;

            // 生成一颗子弹
            BulletData bulletData = new BulletData(GameEntry.Entity.GenerateSerialId(), m_WeaponData.BulletId, m_WeaponData.Owner, m_WeaponData.OwnerCamp, m_WeaponData.Attack, m_WeaponData.BulletSpeed)
            {
                Position = CachedTransform.position
            };
            // 显示子弹
            GameEntry.Entity.ShowBullet(bulletData);
            GameEntry.Sound.PlaySound(m_WeaponData.BulletSoundId);
            
        }
    }
}